
/**
 * 设置localStorage
 * @param key 
 * @param value 
 */
export const setStorage = (key: string, value: any) => {
  let curtime = new Date().getTime();//获取当前时间
  localStorage.setItem(key, JSON.stringify({ val: value, time: curtime }));//转换成json字符串序列
}

/**
 * 获取localStorage
 * @param key 
 * @param exp 
 */
export const getStorage = (key: string, exp: any) =>//exp是设置的过期时间
{
  var val: any = localStorage.getItem(key);//获取存储的元素
  if(!val){
    return null;
  }
  var dataobj = JSON.parse(val);//解析出json对象
  if (new Date().getTime() - dataobj.time > exp)//如果当前时间-减去存储的元素在创建时候设置的时间 > 过期时间
  {
    console.log("expires");//提示过期
    removeStorage(key);
    return null;
  }
  else {
    console.log("val=" + dataobj.val);
    return dataobj.val
  }
}

/**
 * 清除localStorage
 * @param key 
 */
export const removeStorage = (key: string) => {
  localStorage.removeItem(key)
}

/**
 * 清空本地缓存
 */
export const clearStorage = ()=>{
  localStorage.clear()
}